// 上传任务管理器

// 当前正在进行的上传任务列表
let uploadTasks = [];

// 回调函数列表
const callbacks = [];

/**
 * 添加上传任务
 * @param {Object} taskInfo - 任务信息
 * @returns {string} - 任务ID
 */
export const addUploadTask = (taskInfo) => {
  const taskId = Date.now().toString() + Math.floor(Math.random() * 1000);
  const newTask = {
    id: taskId,
    type: taskInfo.type, // 'video' 或 'image'
    name: taskInfo.name,
    size: taskInfo.size,
    progress: 0,
    thumbnail: taskInfo.thumbnail || '',
    status: 'uploading', // 'uploading', 'success', 'error'
    errorMessage: ''
  };
  
  uploadTasks.push(newTask);
  notifyCallbacks();
  
  // 自动显示上传侧边栏
  showUploadSidebar();
  
  return taskId;
};

/**
 * 更新上传任务进度
 * @param {string} taskId - 任务ID
 * @param {number} progress - 进度值 (0-100)
 */
export const updateUploadTaskProgress = (taskId, progress) => {
  const task = uploadTasks.find(t => t.id === taskId);
  if (task && task.status === 'uploading') {
    task.progress = Math.min(100, Math.max(0, progress));
    notifyCallbacks();
  }
};

/**
 * 完成上传任务
 * @param {string} taskId - 任务ID
 * @param {boolean} success - 是否成功
 * @param {string} errorMessage - 错误信息（如果有）
 */
export const completeUploadTask = (taskId, success = true, errorMessage = '') => {
  const taskIndex = uploadTasks.findIndex(t => t.id === taskId);
  if (taskIndex !== -1) {
    const task = uploadTasks[taskIndex];
    task.status = success ? 'success' : 'error';
    task.errorMessage = errorMessage;
    
    notifyCallbacks();
    
    // 成功的任务在短暂显示后移除，错误的任务保留直到用户关闭
    if (success) {
      setTimeout(() => {
        uploadTasks.splice(taskIndex, 1);
        notifyCallbacks();
        
        // 如果没有更多任务，隐藏侧边栏
        if (uploadTasks.length === 0) {
          hideUploadSidebar();
        }
      }, 2000);
    }
  }
};

/**
 * 获取所有上传任务
 * @returns {Array} - 任务列表
 */
export const getUploadTasks = () => {
  return [...uploadTasks];
};

/**
 * 添加任务变化监听回调
 * @param {Function} callback - 回调函数
 * @returns {Function} - 移除监听的函数
 */
export const addUploadTaskListener = (callback) => {
  callbacks.push(callback);
  
  // 立即调用一次，提供当前状态
  callback(getUploadTasks());
  
  // 返回移除监听的函数
  return () => {
    const index = callbacks.indexOf(callback);
    if (index !== -1) {
      callbacks.splice(index, 1);
    }
  };
};

/**
 * 通知所有回调函数
 */
const notifyCallbacks = () => {
  const tasks = getUploadTasks();
  callbacks.forEach(callback => {
    try {
      callback(tasks);
    } catch (error) {
      console.error('上传任务监听器错误:', error);
    }
  });
};

/**
 * 显示上传侧边栏
 */
export const showUploadSidebar = () => {
  // 使用全局组件管理器来挂载侧边栏
  if (typeof window !== 'undefined' && window.Vue && window.Vue.prototype.$globalComponents) {
    try {
      // 尝试挂载侧边栏（如果尚未挂载）
      const sidebar = window.Vue.prototype.$globalComponents.getComponentInstance('UploadSidebar');
      if (!sidebar) {
        window.Vue.prototype.$globalComponents.mountComponentToContainer('UploadSidebar');
      }
    } catch (error) {
      console.error('Failed to show upload sidebar:', error);
    }
  }
};

/**
 * 隐藏上传侧边栏
 */
export const hideUploadSidebar = () => {
  // 使用全局组件管理器来销毁侧边栏
  if (typeof window !== 'undefined' && window.Vue && window.Vue.prototype.$globalComponents) {
    try {
      window.Vue.prototype.$globalComponents.destroyComponent('UploadSidebar');
    } catch (error) {
      console.error('Failed to hide upload sidebar:', error);
    }
  }
};

/**
 * 检查是否有活跃的上传任务
 * @returns {boolean} - 是否有活跃任务
 */
export const hasActiveUploadTasks = () => {
  return uploadTasks.some(task => task.status === 'uploading');
};

/**
 * 清除所有上传任务
 */
export const clearAllUploadTasks = () => {
  uploadTasks = [];
  notifyCallbacks();
};